<template>
  <div >
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-s-promotion"></i> 订单管理</el-breadcrumb-item>
      <el-breadcrumb-item>客房订单</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>
    <template>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="全部订单" name="first" ></el-tab-pane>
        <el-tab-pane label="待确认" name="second" ></el-tab-pane>
        <el-tab-pane label="已完成" name="five" ></el-tab-pane>
        <el-tab-pane label="已关闭" name="six" ></el-tab-pane>
      </el-tabs>
    </template>

    <div>

      <!--      订单编号-->
      <br>
      <el-col >
        <el-col :span="9">
          <template>
            <div class="block">
              <el-date-picker
                  v-model="timeRange"
                  @change="sendTimeRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
              </el-date-picker>
            </div>
          </template>
        </el-col>
        <el-col  :span="6">
          <el-input
              placeholder="请输入用户名搜索"
              v-model="input" @keyup.enter.native="selectByName">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </el-col>
        <el-col :span="9" >
          <el-button type="warning" @click="selectByName">查询</el-button>
          <el-button style="margin-left: 200px" @click="exportExcelSelect">导出Excel</el-button>
<!--          <el-button style="margin-left: 20px" @click="exportAllData">导出全部数据</el-button>-->
        </el-col>
      </el-col>


      <template>
        <!--原始表格-->
        <el-table
            :data="tableData"
            @selection-change="handleSelectionChange">
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="用户名" prop="name" width="100px" align="center"></el-table-column>
          <el-table-column label="身份证号" prop="cardNum" align="center"></el-table-column>
          <el-table-column label="联系电话" prop="phoneNum" align="center"></el-table-column>
          <el-table-column label="订单编号" prop="orderId" align="center"></el-table-column>
          <el-table-column label="入住时间" prop="checkInDate"  align="center"></el-table-column>
          <el-table-column label="离店时间" prop="checkOutDate" align="center"></el-table-column>
          <el-table-column label="房型" prop="roomType" width="80px" align="center"></el-table-column>
          <el-table-column label="价格" prop="price" width="100px" align="center"></el-table-column>
          <el-table-column label="实付金额" prop="amountPaid" width="80px" align="center"></el-table-column>
          <el-table-column label="订单状态" prop="orderStatus" width="80px" align="center" :data="orderList">
            <template slot-scope="scope">
              {{ getOrderStatusText(scope.row.orderStatus) }}
            </template>
          </el-table-column>
          <el-table-column
              align="right">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  @click="handleEdit(scope.row)">查看订单</el-button>
              <el-button
                  size="mini"
                  type="danger"
                  @click="open(scope.row)">删除订单</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--预览弹窗表格-->
        <el-dialog title="表格保存预览" width="70%" :visible.sync="selectWindow">
          <el-table
              :data="selectData"
              height="380px"
              id="selectTable">
            <el-table-column label="用户名" prop="name" width="100px" align="center"></el-table-column>
            <el-table-column label="身份证号" prop="cardNum" align="center"></el-table-column>
            <el-table-column label="联系电话" prop="phoneNum" align="center"></el-table-column>
            <el-table-column label="订单编号" prop="orderId" align="center"></el-table-column>
            <el-table-column label="入住时间" prop="checkInDate"  align="center"></el-table-column>
            <el-table-column label="离店时间" prop="checkOutDate"  align="center" ></el-table-column>
            <el-table-column label="房型" prop="roomType" width="80px" align="center"></el-table-column>
            <el-table-column label="价格" prop="price" width="100px" align="center"></el-table-column>
            <el-table-column label="实付金额" prop="amountPaid" width="80px" align="center"></el-table-column>
            <el-table-column label="订单状态" prop="orderStatus" width="80px" align="center" :data="orderList">
              <template slot-scope="scope">
                {{ getOrderStatusText(scope.row.orderStatus) }}
              </template>
            </el-table-column>
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="exportExcel">确定保存</el-button>
          </div>
        </el-dialog>
      </template>

      <template>

        <div class="block">
          <br>
          <el-pagination
              @current-change="changePage"
              :page-size="pageSize"
              hide-on-single-page
              layout="total,  prev, pager, next, jumper"
              :current-page="currentPage"
              :total="total">
          </el-pagination>
        </div>
      </template>

    </div>

  </div>
</template>


<script>
import axios from "axios";
import moment from 'moment';
import FileSaver from "file-saver";
import XLSX from "xlsx";
//   import * as XLSX from 'xlsx/xlsx.mjs';

export default {
  data() {
    return {
      drawer: false,
      direction: 'ttb',
      orderList: [
        { orderStatus: 0 },
        { orderStatus: 1 },
        { orderStatus: 2 },
        // 其他订单数据...
      ],
      baseUrl:'http://localhost:29182//hotel/order',
      input:'',
      total:0,
      pageSize:0,
      currentPage: 0,
      //全部订单行
      activeName: 'first',
      tableData: [],
      //表格中选中的数据
      selectData: [],
      selectWindow: false,
      allDataSelected: false,
      search: '',
      value1: '',
      timeRange: [], // 新增的属性，用于保存时间区间
      page:'',
      orderStatus:''
    };
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },
    //订单状态改变绑定
    getOrderStatusText(status) {
      if (status === 1) {
        return '已完成';
      } else if (status === 2) {
        return '已关闭';
      } else {
        return '待确认';
      }
      // 其他状态...
    },
    //  通过用户名搜索订单  搜索功能
    selectByName(){
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }
      let url = this.baseUrl+'/selectbyname?name=' + this.input+'&page='+page;
      console.log('url = ' + url);
      axios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
          console.log("跳转成功");
        }
      });
    },

    //导出全部数据  excel
    exportAllData() {
      if (this.tableData.length < 1) {
        this.$message.error('没有数据可导出！');
        return false;
      }
      if (this.allDataSelected) {
        this.selectData = this.tableData;
      } else {
        this.selectData = [];
      }
      this.selectWindow = true;
    },

    //格式化数据
    getExcel(dom, title = '默认标题',) {
      var excelTitle = title;
      var wb = XLSX.utils.table_to_book(document.querySelector(dom));
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, { bookType: "xlsx", bookSST: true, type: "array" });
      try {
        FileSaver.saveAs(
            new Blob([wbout], { type: "application/octet-stream" }),
            excelTitle + ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },

    //导出
    exportExcel() {
      this.getExcel('#selectTable', '导出的自定义标题')
    },
    //显示预览弹窗
    exportExcelSelect() {
      if (this.selectData.length < 1) {
        this.$message.error('请选择要导出的内容！');
        return false;
      }
      if (this.selectData.length === this.tableData.length) {
        this.allDataSelected = true;
      } else {
        this.allDataSelected = false;
      }
      this.selectWindow = true;
    },

    //选中数据
    handleSelectionChange(val) {
      this.selectData = val;
    },


      //  时间查询方法
      sendTimeRange() {
        console.log("DATE:" + this.timeRange)
        let page = this.$router.currentRoute.query.page;
        if (!page) {
          page = 1;
        }
        let url =this.baseUrl+ '/selectTime?page=' + page;

        console.log('url = ' + url);

        // 发送请求到后端
        this.axios.post(url, this.timeRange).then(response => {
          let jsonResult = response.data;
          if (jsonResult.state == 20000) {
            this.tableData = jsonResult.data.list;
            this.total = jsonResult.data.total;
            this.pageSize = jsonResult.data.pageSize;
            this.currentPage = jsonResult.data.currentPage;
          }
        }).catch(error => {
          let title = '错误';
          let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
          this.$alert(message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          console.log(error);
        });

      },

//  日期转换格式
     /* formatDate(row, column) {
        /!* const date = new Date(row.checkInDate);
      return new Date(date).toLocaleString('en-CN', {timeZone: 'Asia/Shanghai'});*!/
        // return moment(row.date).utcOffset(8).format('YYYY-MM-DD');
        return moment(row.date).format('YYYY-MM-DD');
      },*/
//标签页
      handleClick(tab) {
        if (tab.label ==="全部订单") {
          this.loadGoodsList(5);
        }
        if (tab.label === "待确认") {
          this.loadGoodsList(0);
        }
        if (tab.label === "已完成") {
          this.loadGoodsList(1);
        }
        if (tab.label === "已关闭") {
          this.loadGoodsList(2);
        }
      },

      changePage(page) {
        //todo 需要在订单界面添加用户信息的字段
// todo  userid需要根据实际情况修改
        this.$router.replace('?&page=' + page);
        let orderStatus = 0;
        switch (this.activeName) {
          case 'first':
            orderStatus = 5
            break;
          case 'second':
            orderStatus = 0
            break;
          case 'five':
            orderStatus = 1
            break;
          case 'six':
            orderStatus = 2
            break;

          default:
            break;
        }
        if (this.input==''){
          this.loadGoodsList(orderStatus);
        }else if (this.input!=''){
          this.selectByName()
        }else if (timeRange!=''){
          this.sendTimeRange()
        }
      },

    //通过id查询订单
      handleEdit(order) {
        // 使用路由跳转到另一个页面
        if (order.orderStatus===0){
          this.$router.push({ path: '/admin/order/detail/start', query: { order: JSON.stringify(order) } });
        };
        if (order.orderStatus===1){
          this.$router.push({ path: '/admin/order/detail/finish', query: { order: JSON.stringify(order) } });
        };
        if (order.orderStatus===2){
          this.$router.push({ path: '/admin/order/detail/close', query: { order: JSON.stringify(order) } });
        };
      },
    //通过id查询订单

      handleselect(order){
      let url = this.baseUrl+' /select/' + order.id;
      console.log('url = ' + url);
      axios.get(url).then((response) => {
        let orderdetail='';
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          orderdetail=jsonResult.data;
          console.log("跳转成功");
        }
      });
    },
      // 删除操作
      open(order) {
        let message = '此操作将永久删除' + order.orderId + '是否继续?'
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.handleDelete(order);
        })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });
            });
      },
      // 执行删除
      handleDelete(order) {
        // let url = this.baseUrl.ADMIN_MALL ++ '/goods/' + goods.id + '/delete';
        let url =this.baseUrl+ '/delete/' + order.id;
        console.log('url = ' + url);
        axios.post(url).then((response) => {
          let jsonResult = response.data;
          if (jsonResult.state == 20000) {
            this.$message({
              message: '删除成功！',
              type: 'success'
            });
            let orderStatus = 0;
            switch (this.activeName) {
              case 'first':
                orderStatus = 5
                break;
              case 'second':
                orderStatus = 0
                break;
              case 'five':
                orderStatus = 1
                break;
              case 'six':
                orderStatus = 2
                break;

              default:
                break;
            }
            this.loadGoodsList(orderStatus);
          } else if (jsonResult.state == 40400) {
            this.$alert(jsonResult.message, '错误', {
              confirmButtonText: '确定',
              callback: action => {
                this.loadGoodsList();
              }
            });
          } else {
            this.$alert(jsonResult.message, '错误', {
              confirmButtonText: '确定',
              callback: action => {
              }
            });
          }
        }).catch(error => {
          let title = '错误';
          let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
          this.$alert(message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          console.log(error);
        });
      },

      // 加载商品列表
      loadGoodsList(orderStatus) {
        let page = this.$router.currentRoute.query.page;
        if (!page) {
          page = 1;
        }

        let url = this.baseUrl+'/selectOrder?orderStatus=' + orderStatus + '&page=' + page;

        console.log('url = ' + url);

        axios.get(url).then((response) => {
          let jsonResult = response.data;
          if (jsonResult.state == 20000) {
            this.tableData = jsonResult.data.list;
            this.total = jsonResult.data.total;
            this.pageSize = jsonResult.data.pageSize;
            this.currentPage = jsonResult.data.currentPage;
          }
        }).catch(error => {
          let title = '错误';
          let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
          this.$alert(message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          console.log(error);
        });
      }
    },
    mounted() {
      // const page = this.$route.query.page;
 /*     localStorage.setItem('currentPage', page);
      const currentPage = parseInt(localStorage.getItem('currentPage')) || 1;*/
      // if ()
         this.loadGoodsList(5);
    }


  }

</script>
<style>
@media (max-width: 768px) {
  .el-button {
    display: block;
    width: 100%;
    margin-bottom: 10px;
  }
}
</style>





